const App = getApp();
const func = require('../../utils/func');
import wxParse from '../../wxParse/wxParse.js'; // 富文本插件
let globalData = getApp().globalData;

// 会员折扣
let usersDiscount = 1;
// 记录规格的数组
let productSpecValueID = [];

Page({
	data: {
		height: 64, //header高度
		specBaozhang: false,
		showVideo:false,
		huanxiu: false,
		spechuan: '',
		huanxiu2: false,
		scrollbar: false,
		enhanced: true,
		top: 26, //标题图标距离顶部距离
		scrollH: 0, //滚动总高度
		opcity: 0,
		iconOpcity: 0.5,
		specColor: 1,
		isCollect: 0, //收藏标签   1是已收藏    2是为收藏
		Showposter: false, //海报展示
		popuptype:'parameter',   //点击弹窗某一弹窗
		// coponList:[
		//     {label:'1',name:'满99减8'},
		//     {label:'2',name:'满59减5'}
		// ],
		tips: [{
				label: '1',
				name: '可配送海外'
			},
			{
				label: '2',
				name: '店铺发货&售后'
			},
			{
				label: '3',
				name: '7天无理由退货'
			},
			{
				label: '4',
				name: '闪电退款'
			},
			{
				label: '5',
				name: '极速审核'
			},
		],
		Showshare: false,
		specSize: 1,
		posterImg: '',
		//1-已结束，2-正在进行，3-即将开抢
		status: 2,
		//1-未设提醒 2-已设提醒
		remind: 1,
		autoplay: false,
		closeShow: false,
		sc:true,

		// 是否加载中
		isLoading: true,
		// 商品ID
		goodsID: 0,
		// 商品全部数据
		goodsData: [],
	
		// 商品轮播图数据
		goodsImagesIndex: 0,
		goodsImagesList: [],
		// 商品规格参数
		goodsMultiSpec: [],
		goodsSpecShow: false,
		// 购买数量
		goodsBuyQuantity: 1,
		// 购物车商品数量
		cartTotalNum: 0,
		// poster:'/static/images/haibao.png'
	},

	onLoad: function(options) {
		var _this = this;
		_this.setData({
			status: options.status || 2
		});
		let obj = wx.getMenuButtonBoundingClientRect()
		setTimeout(() => {
			wx.getSystemInfo({
				success: res => {
					_this.setData({
						width: obj.left || res.windowWidth,
						height: obj.top ? obj.top + obj.height + 8 : res
							.statusBarHeight + 44,
						top: obj.top ? obj.top + (obj.height - 32) / 2 : res
							.statusBarHeight + 6,
						scrollH: res.windowWidth,
						topHeight:obj.height
					}, () => {
						globalData.navigationBarWidth = _this.data.width
						globalData.navigationBarHeight = _this.data.height
						globalData.statusBarHeight = res.statusBarHeight
					})
				}
			});
        }, 0);
        
		let scene = decodeURIComponent(options.scene);
		if(scene != 'undefined'){
			let scene_arr = scene.split("=");
			options.goodsID = scene_arr[1];
		}
		// 获取商品ID
        _this.data.goodsID = options.goodsID ? parseInt(options.goodsID) : 0;
        
		// 获取商品信息
		_this.getGoodsData();
	},

	// 配送选择弹窗
	showPopupList(e){
		let _this = this;
		_this.setData({
			popuptype:e.currentTarget.dataset.popuptype,
			PopupListPopup:!_this.data.PopupListPopup
		})
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {
		let _this = this;
		_this.getGoodsData(); // 获取页面数据
		// 下拉刷新
		wx.stopPullDownRefresh();
	},

	// 轮播图图片坐标
	imagesChange: function(e) {
		var _this = this;
		_this.setData({
			goodsImagesIndex: e.detail.current
		});
		_this.loginout()
	},

	catchtouchmove(){
		return false
	},

	// 轮播图图片放大
	imagesPreview: function(e) {
		let _this = this;
		let index = e.currentTarget.dataset.index,
			imageUrls = [];
			_this.data.goodsImagesList.forEach(item => {
				imageUrls.push(item.image_url);
			});
			wx.previewImage({
				urls: imageUrls,
				current: imageUrls[index],
			})
	},

	// 获取商品信息
	getGoodsData() {
		let _this = this;
		App._requestApi(_this, App.globalData.config.apiViewUrl, {
			aid: _this.data.goodsID,
			apiCollect: `ekey=1&type=default`, // 文档是否收藏标签，1：已收藏，0：未收藏
			apiGoodCoupon: `ekey=1&detail_get=1`,
			apiCommentList: `ekey=1&pagesize=2`, //2条评价
			apiAddFootprint: `ekey=1` //添加足迹
		}, function(res) {
			if (false == res.data.detail.data) {
				App.showError('商品不存在');
			} else {
				let goodsData = res.data.detail.data,
					isCollect = res.data.apiCollect[1].is_collect,
					goodsImagesList = goodsData.image_list ? goodsData.image_list : [],
					cartTotalNum = res.data.cart_total_num ? res.data.cart_total_num : 0,
					couponList = res.data.apiGoodCoupon[1],
					commentTotal = res.data.apiCommentList[1].total,
					config = res.data.config,
					mobile = res.data.users.mobile,
					commentList = res.data.apiCommentList[1].data;
				_this.setData({
					isLoading: false,
					isCollect: isCollect,
					goodsData: goodsData,
					mobile,
					cartTotalNum: cartTotalNum,
					goodsImagesList: goodsImagesList,
					couponList,
					config,
					commentList,
					commentTotal
				});

				// 富文本转码
				if (goodsData.content.length > 0) wxParse.wxParse('content', 'html', goodsData.content,
					_this, 0);

				// 商品规格处理
				_this._goodsSpecHandle(goodsData);

				// 更新商品规格信息
				_this._goodsSpecUpdate();
				
				wx.setNavigationBarTitle({
					title: goodsData.title
				})
			}
		});
	},

	// 商品规格值处理
	_goodsSpecHandle(goodsData) {
		var _this = this;
		var goodsMultiSpec = goodsData.spec_attr;
		// 商品规格值ID处理
		if (goodsMultiSpec.select_spec_data.spec_value_id) {
			productSpecValueID = goodsMultiSpec.select_spec_data.spec_value_id;
			goodsData.spec_value_id = goodsMultiSpec.select_spec_data.spec_value_id.join('_');
		}
		// 会员折扣率
		if (goodsMultiSpec.select_spec_data.users_discount) {
			usersDiscount = goodsMultiSpec.select_spec_data.users_discount;
		}

		// 规格名称、规格值处理
		var specNameList = [];
		var specValueList = [];
		var specDataList = goodsMultiSpec.spec_data;
		for (let i in specDataList) {
			specNameList.push(specDataList[i].spec_name);
			specDataList[i].spec_data_new.forEach((item, index) => {
				if (item.checked == true) specValueList.push(item.spec_value);
			});
		}
		_this.setData({
			specNameList: specNameList,
			specValueList: specValueList,
			goodsMultiSpec: goodsMultiSpec,
		});
	},

	// 更新商品规格信息
	_goodsSpecUpdate() {
		let _this = this;
		// 获取详情数据
		let goodsData = _this.data.goodsData;
		// 匹配选中的规格，读取出数组
		let specValueID = productSpecValueID;
		specValueID = specValueID.sort(function(a, b) {
			return a - b;
		}).join('_');
		let goodsMultiSpec = _this.data.goodsMultiSpec.spec_value;
		let specValueData = goodsMultiSpec.find((val) => {
			return val.spec_value_id == specValueID;
		});

		// 更新商品规格销售价、划线价、库存量、销售量信息
		if (typeof specValueData === 'object') {
			// 更新销售价
			let specPrice = specValueData.spec_price;
			specPrice = Number(specPrice) * Number(usersDiscount);
			goodsData.users_price = specPrice.toFixed(2);
			goodsData.users_price_arr = goodsData.users_price.split('.');
			// 更新商品原价
			goodsData.old_price = Number(specValueData.spec_price);
			// 更新划线价
			let marketPrice = specValueData.market_price;
			marketPrice = Number(marketPrice) * Number(usersDiscount);
			goodsData.market_price = marketPrice.toFixed(2);
			// 更新库存量
			goodsData.stock_count = specValueData.spec_stock;
			// 更新销售量
			let specSalesNum = specValueData.spec_sales_num;
			goodsData.goods_sales = Number(goodsData.virtual_sales) + Number(specSalesNum);
			// 更新所选规格值ID
			goodsData.spec_value_id = specValueID;
			// 更新详情数据
			_this.setData({
				goodsData: goodsData
			});
		} else {
			// 更新销售价
			goodsData.users_price = Number(goodsData.users_price) * Number(usersDiscount);
			goodsData.users_price = goodsData.users_price.toFixed(2);
			goodsData.users_price_arr = goodsData.users_price.split('.');
			// 更新销售量
			goodsData.goods_sales = Number(goodsData.sales_num);
			// 更新详情数据
			_this.setData({
				goodsData: goodsData
			});
		}
	},

	// 显示、关闭规格弹窗
	goodsSpecShowPopup: function(e) {
		var _this = this;
		_this.setData({
			type:e.currentTarget.dataset.type,
			goodsSpecShow: !_this.data.goodsSpecShow
		});
	},

	// 点击切换不同规格
	goodsSpecSwitch(e) {
		let _this = this,
			specIdx = e.currentTarget.dataset.specIdx,
			itemIdx = e.currentTarget.dataset.itemIdx,
			goodsMultiSpec = _this.data.goodsMultiSpec;
			let specValueList = _this.data.specValueList;
			for (let i in goodsMultiSpec.spec_data) {
				for (let j in goodsMultiSpec.spec_data[i].spec_data_new) {
					if (specIdx == i) {
						goodsMultiSpec.spec_data[i].spec_data_new[j].checked = false;
						if (itemIdx == j) {
							goodsMultiSpec.spec_data[i].spec_data_new[itemIdx].checked = true;
							let specValue = goodsMultiSpec.spec_data[i].spec_data_new[itemIdx].spec_value;
							specValueList[specIdx] = specValue;
						}
					}
					if (true === goodsMultiSpec.spec_data[i].spec_data_new[j].checked) {
						productSpecValueID[i] = goodsMultiSpec.spec_data[i].spec_data_new[j].spec_value_id;
					}
				}
			}
			_this.setData({
				specValueList: specValueList,
				goodsMultiSpec: goodsMultiSpec,
			});

		// 更新商品规格信息
		_this._goodsSpecUpdate();
	},

	// 购买数量
	buyQuantity: function(e) {
		var _this = this;
		_this.setData({
			goodsBuyQuantity: e.detail.value
		});
	},

	//获取手机号
	getPhoneNumber(e) {
		let _this = this;
		if ('getPhoneNumber:ok' == e.detail.errMsg) {
			let _this = this;
			App._requestPost(_this, App.globalData.config.getWeChatPhoneCodeUrl, {
					code: e.detail.code,
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv,
					notBind: 1
				},
				function (res) {
					_this.setData({
						mobile:res.data.phoneNumber
					})
				}
			);
		}
		let type = 'buyNow'
		_this.goodsConfirmSubmit(type)
	},

	// 添加收藏/取消收藏
	goodsCollect(e) {
		let _this = this;
		App._requestApi(_this, App.globalData.config.apiGetCollectUrl, {
			aid: _this.data.goodsID,
		}, function(res) {
			if (res.code === 1) {
				_this.setData({
					isCollect: res.data.is_collect
				});
			} else {
				App.showError(res.msg);
			}
		});
	},

	// 加入购物车and立即购买
	goodsConfirmSubmit(e) {
		let _this = this;
		// 提交类型
		if (e == 'buyNow') {
			let submitType = e;
			_this.setData({
				submitType
			})
		} else {
			let submitType = e.currentTarget.dataset.type;
			_this.setData({
				submitType
			})
		}
		// 提交数据
		let goodsData = _this.data.goodsData;
		let goodsBuyQuantity = _this.data.goodsBuyQuantity;
		let postData = {
			product_id: goodsData.aid,
			product_num: goodsBuyQuantity,
			spec_value_id: goodsData.spec_value_id ? goodsData.spec_value_id : 0
		};

		// 发起提交
		if ('addCart' == _this.data.submitType) {
			postData['action'] = 'addCart';
			App._requestApi(_this, App.globalData.config.shopCartActionUrl, postData,
				function(res) {
					_this.setData({
						cartTotalNum: res.data.cart_total_num,
						goodsSpecShow: !_this.data.goodsSpecShow
					});
					App.showSuccess('已添加至购物车');
				},
				function(res) {
					App.showError(res.msg);
				}
			);
		} else if ('buyNow' == _this.data.submitType) {
			App._requestApi(_this, App.globalData.config.shopGoodsBuyNowUrl, postData,
				function(res) {
					wx.navigateTo({
						url: res.url
					});
					_this.setData({
						goodsSpecShow: !_this.data.goodsSpecShow
					});
				},
				function(res) {
					App.showError(res.msg);
				}
			);
		} else if ('specType' == _this.data.submitType) {
			_this.setData({
				showBottomPopup: !_this.data.showBottomPopup
			})
		}
	},

	// 展示分享弹窗
	sharePopup(e) {
		this.setData({
			Showshare: !this.data.Showshare
		})
	},
	// 展示海报弹窗
	posterPopup(e) {
		this.setData({
			Showposter: !this.data.Showposter,
			Showshare: false,
		})
	},
	// 生成商品二维码海报
	createGoodsShareQrcodePoster: function() {
		let _this = this;
		_this.setData({
			Showposter: !_this.data.Showposter,
			Showshare: false
		});
		wx.showLoading({
			title: '加载中'
		});
		// 提交数据
		App._requestPost(_this, App.globalData.config.apiCreateGoodsShareQrcodePosterUrl, {
				aid: _this.data.goodsID
			},
			function(res) {
				let posters = res.data;
				_this.setData({
					poster: posters.poster,
				});
			},
			function(res) {
				App.showError(res.msg);
			}
		);
	},
	 // 长按保存二维码
	 savePic(e) {
		wx.showToast({
			icon: 'loading',
			title: '正在保存图片',
			duration: 1000
		});
		wx.getSetting({
			success: (res) => {
				if (!res.authSetting['scope.writePhotoAlbum']) {
					wx.authorize({
						scope: 'scope.writePhotosAlbum',
						success: () => {
							this.saveImg1();
						},
						fail: () => {}
					});
				} else {
					this.savePic();
				}
			},
			fail: (res) => {}
		});
	},

	saveImg1() {
		let _this = this;
		wx.downloadFile({
			// 图片下载地址
			url: _this.data.poster,
			// url: app.apiUrl.url + 'Userequity/poster',
			success: function (res) {
				wx.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,

					success(res) {
						wx.showToast({
							title: '保存成功',
							icon: 'success',
							duration: 1000
						});
					}
				});
			}
		});
	},
	/**
	 * 分享当前页面
	 */
	onShareAppMessage() {
		let _this = this;
		return {
			title: _this.data.goodsData.title,
			path: "/pages/product/detail?goodsID=" + _this.data.goodsData.aid + '&' + App.getShareUrlParams()
		};
	},
	/**
	 * 分享到朋友圈
	 */
	onShareTimeline() {
		let _this = this;
		return {
			title: _this.data.goodsData.title,
		}
	},
	back: function() {

		wx.navigateBack({
          delta: 0,
        })
	},
	pause(e) {
		this.setData({
			autoplay: true
		})
	},
	play(e) {
		let _this = this;
		_this.setData({
			playBtn:true
		})
		
	},
	showVideo(e){
		let _this = this
		_this.setData({
			videoIndex:e.currentTarget.dataset.index,
			showVideo:true
		})
		_this.play()
	},
	// 退出播放按钮
	loginout() {
		let _this = this;
		_this.setData({
			showVideo:false,
			playBtn:false
		})
	},
	onPageScroll(e) {
		let scroll = e.scrollTop <= 0 ? 0 : e.scrollTop;
		let opcity = scroll / this.data.scrollH;
		if (this.data.opcity >= 1 && opcity >= 1) {
			return;
		}
		this.setData({
			opcity: opcity,
			iconOpcity: 0.5 * (1 - opcity < 0 ? 0 : 1 - opcity)
		})
	},

	// 跳转到其他界面
	jumpToView(e) {
		func.jumpToUrl(e);
	}
})